<template>
    <div>
        <div>
            <el-form ref="searchForm" :inline="true" :model="condition.search" label-suffix="" label-width="100px"
                     label-position="left" size="small">
                <el-row>
                    <el-col :span=6>
                        <el-form-item label="推广名称" prop="launchName">
                            <el-select v-model="condition.search.launchId" placeholder="请选择" clearable>
                                <el-option
                                    v-for="item in plans"
                                    :key="item.id"
                                    :label="item.launchName"
                                    :value="item.launchId === 0 ? -1 : item.launchId">
                                    {{ item.launchName }}
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="数据日期" prop="syncDate">
                            <el-date-picker
                                v-model="condition.search.syncDate"
                                type="date"
                                placeholder="同步日期"
                                value-format="yyyy-MM-dd"
                                align="right">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="时间维度" prop="type">
                            <el-select v-model="condition.search.timeUnit" clearable
                                       placeholder="时间维度">
                                <el-option label="按天"
                                           value="day"></el-option>
                                <el-option label="按小时"
                                           value="hour"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span=6>
                        <el-form-item label="平台" prop="platform">
                            <el-select v-model="condition.search.platform" clearable
                                       placeholder="平台">
                                <el-option label="双平台"
                                           value="0"></el-option>
                                <el-option label="点评"
                                           value="1"></el-option>
                                <el-option label="美团"
                                           value="2"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col>
                        <el-form-item>
                            <el-button type="success" v-on:click="sync">同步</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" v-on:click="getData">查询</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" v-on:click="reset">重置</el-button>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" v-on:click="exportExcel">导出</el-button>
                        </el-form-item>
                        <el-form-item v-if="mode === 'simple'">
                            <el-button type="success" v-on:click="switchMode">显示所有字段</el-button>
                        </el-form-item>
                        <el-form-item v-if="mode !== 'simple'">
                            <el-button type="warning" v-on:click="switchMode">显示部分字段</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <el-tabs v-model="activeName">
            <el-tab-pane label="门店维度" name="shopDimension">
                <dp-cpc-report-table
                    ref="shopDimension"
                    dimension="shop"
                    :shop-id="shopId"
                    :shop-name="shopName"
                    :mode="mode"
                    :sync-date="condition.search.syncDate"
                    :time-unit="condition.search.timeUnit"
                    :platform="condition.search.platform">
                </dp-cpc-report-table>
            </el-tab-pane>
            <el-tab-pane label="推广维度" name="launchDimension">
                <dp-cpc-report-table
                    ref="launchDimension"
                    dimension="launch"
                    :shop-id="shopId"
                    :shop-name="shopName"
                    :mode="mode"
                    :sync-date="condition.search.syncDate"
                    :launch-id="condition.search.launchId"
                    :time-unit="condition.search.timeUnit"
                    :platform="condition.search.platform">
                </dp-cpc-report-table>
            </el-tab-pane>
            <el-tab-pane label="关键词维度" name="keywordDimension">
                <dp-cpc-report-table
                    ref="keywordDimension"
                    dimension="keyword"
                    :shop-id="shopId"
                    :shop-name="shopName"
                    :mode="mode"
                    :sync-date="condition.search.syncDate"
                    :launch-id="condition.search.launchId"
                    :time-unit="condition.search.timeUnit"
                    :platform="condition.search.platform">
                </dp-cpc-report-table>
            </el-tab-pane>
            <el-tab-pane label="所有维度" name="allDimension">
                <dp-cpc-report-table
                    ref="allDimension"
                    :shop-id="shopId"
                    :shop-name="shopName"
                    :mode="mode"
                    :sync-date="condition.search.syncDate"
                    :launch-id="condition.search.launchId"
                    :time-unit="condition.search.timeUnit"
                    :platform="condition.search.platform">
                </dp-cpc-report-table>
            </el-tab-pane>
        </el-tabs>

        <el-dialog title="同步数据" width="40%" :visible.sync="syncDialogVisible">
            <el-form :model="syncForm" label-width="150px" size="small">
                <el-form-item label="请选择推广">
                    <el-select v-model="syncForm.launchId" placeholder="请选择" clearable>
                        <el-option
                            v-for="item in plans"
                            :key="item.id"
                            :label="item.launchName"
                            :value="item.launchId">
                            {{ item.launchName }}
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="请选择同步日期">
                    <el-select v-model="syncForm.daysType" placeholder="请选择" clearable>
                        <el-option label="昨天" value="YESTERDAY"></el-option>
                        <el-option label="近三天" value="THREE"></el-option>
                        <el-option label="近七天" value="SEVEN"></el-option>
                        <el-option label="近十天" value="TEN"></el-option>
                        <el-option label="近30天" value="THIRTY"></el-option>
                        <el-option label="自定义" value="USER_DEFINE"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="请选择日期" v-if="syncForm.daysType === 'USER_DEFINE'">
                    <el-date-picker
                        v-model="syncForm.dateRange"
                        value-format="yyyy-MM-dd"
                        unlink-panels
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        :picker-options="this.CONST.analysis_date_options">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="请选择平台" prop="platform">
                    <el-select v-model="syncForm.platform" clearable
                               placeholder="平台">
                        <el-option label="所有（耗时较长）"
                                   value="-1"></el-option>
                        <el-option label="双平台"
                                   value="0"></el-option>
                        <el-option label="点评"
                                   value="1"></el-option>
                        <el-option label="美团"
                                   value="2"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否同步门店维度">
                    <el-switch v-model="syncForm.shopDimensionFlag"></el-switch>
                </el-form-item>
                <el-form-item label="是否同步关键字维度">
                    <el-switch v-model="syncForm.keywordDimensionFlag"></el-switch>
                </el-form-item>
                <el-form-item label="是否同步分时维度">
                    <el-switch v-model="syncForm.hoursDimensionFlag"></el-switch>
                    <div class="form-tips">如果同步分时，需要耗时较长</div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="syncDialogVisible = false" size="small">取 消</el-button>
                <el-button @click="syncConfirm" type="primary" size="small">确 定</el-button>
            </div>
        </el-dialog>
        <el-divider content-position="left">数据分析</el-divider>
        <dp-cpc-analysis :shop-id="shopId" :shop-name="shopName" :launch-id="launchId"></dp-cpc-analysis>
    </div>
</template>

<script>
import {
    addDpCpcReport,
    deleteDpCpcReport,
    getDpCpcPlanByShopId,
    getDpCpcPlanFields,
    syncDpCpcReport,
    updateDpCpcReport
} from '@/api/api'
import DpCpcAnalysis from "@/component/analysis/DpCpcAnalysis";
import DpCpcReportTable from "@/component/DpCpcReportTable";

export default {
    name: "DpCpcReport",
    components: {DpCpcAnalysis, DpCpcReportTable},
    data() {
        return {
            // 分页搜索条件
            condition: {
                page: 1,
                rows: 10,
                total: 0,
                search: {
                    platform: '0',
                    timeUnit: 'day',
                    launchId: -1,
                }
            },
            // 表格数据
            tableData: [],
            // 新增或者编辑对话框显示
            addOrUpdateDialogVisible: false,
            // 标题
            addOrUpdateDialogTitle: '新增',
            // 新增或者编辑对话框表单
            addOrUpdateForm: {},
            // 选中行
            selectedRow: {},

            syncDialogVisible: false,
            syncForm: {
                daysType: '',
                shopDimensionFlag: true,
                keywordDimensionFlag: false,
                hoursDimensionFlag: false,
            },

            // 字段信息
            fields: this.CONST.cpc_fields,
            // 排序前的数据
            beforeOrderTableData: [],

            // 推广计划
            plans: [],

            activeName: 'shopDimension',

            // 默认简单模式
            mode: 'simple',
        }
    },
    // 这里定义需要父组件传过来的东西
    props: {
        shopId: String,
        shopName: String,
        launchId: Number,
        size: {
            type: String,
            default: 'small'
        },
    },
    watch: {
        shopName: function (val, oldVal) {
            this.shopName = val;
        }
    },
    methods: {
        switchMode() {
            if (this.mode === 'simple') {
                this.mode = 'all';
            } else {
                this.mode = 'simple';
            }
        },
        // 渲染头部
        renderHeader(h, {column, $index}, item) {
            return [column.label, h(
                'el-tooltip',
                {
                    props: {
                        content: item.desc,
                        placement: 'top'
                    },
                },
                [h('span', {class: {'el-icon-question': true}})]
            )]
        },
        // 排序
        onSortChange({prop, order}) {
            if (order != null) {
                if (this.beforeOrderTableData.length === 0) {
                    this.beforeOrderTableData = this.tableData.concat();
                }
                this.tableData.sort(this.compare(prop, order));
            } else {
                this.tableData = this.beforeOrderTableData.concat();
            }
        },
        // 排序函数
        compare(propertyName, sort) {
            let _this = this;
            return function (obj1, obj2) {
                let value1 = obj1[propertyName]
                let value2 = obj2[propertyName]
                if (typeof value1 === 'string' && typeof value2 === 'string') {
                    if (value1.indexOf('%') !== -1 && value2.indexOf('%') !== -1) {
                        value1 = _this.toPoint(value1);
                        value2 = _this.toPoint(value2);
                    }
                }
                if (typeof value1 === 'string' && typeof value2 === 'string') {
                    const res = value1.localeCompare(value2, 'zh')
                    return sort === 'ascending' ? res : -res
                } else {
                    if (value1 <= value2) {
                        return sort === 'ascending' ? -1 : 1
                    } else if (value1 > value2) {
                        return sort === 'ascending' ? 1 : -1
                    }
                }
            }
        },
        // 百分数转化为小数
        toPoint(percent) {
            let str = percent.replace("%", "");
            str = str / 100;
            return str;
        },
        sync() {
            this.syncDialogVisible = true;
        },
        syncConfirm() {
            this.syncForm.shopId = this.shopId;
            if (this.syncForm.daysType === 'USER_DEFINE') {
                this.syncForm.startDate = this.syncForm.dateRange[0];
                this.syncForm.endDate = this.syncForm.dateRange[1];
            }
            syncDpCpcReport(this.syncForm).then(data => {
                if (data.respCode == 1000) {
                    this.$message({
                        type: 'success',
                        message: '提交同步请求成功，系统正在后台同步数据，大约需要您等待1-2分钟!'
                    });
                    this.syncDialogVisible = false;
                    this.getData();
                }
            })
        },
        // 这里可以单独设置每一行的样式
        tableRowClassName({row, rowIndex}) {
            return '';
        },
        handleSizeChange(val) {
            this.getData();
        },
        handleCurrentChange(val) {
            this.getData();
        },
        // 格式布尔值
        formatBoolean: function (row, column, cellValue) {
            if (cellValue) {
                return "是";
            } else {
                return "否";
            }
        },
        formatPlatform: function (row, column, cellValue) {
            if (cellValue == '0') {
                return "双平台";
            } else if (cellValue == '1') {
                return "点评";
            } else if (cellValue == '2') {
                return "美团";
            } else {
                return "未知";
            }
        },
        showAddDialog: function () {
            this.addOrUpdateDialogTitle = '新增';
            this.addOrUpdateDialogVisible = true;
            this.addOrUpdateForm = {};
        },
        showUpdateDialog: function (row) {
            this.addOrUpdateDialogTitle = '编辑';
            this.addOrUpdateDialogVisible = true;
            this.selectedRow = row;
            // 深拷贝
            this.addOrUpdateForm = Object.assign({}, row);
        },
        reset: function () {
            this.$refs['searchForm'].resetFields();
        },
        exportExcel: function () {
            this.$refs[this.activeName].exportExcel();
        },
        add: function () {
            addDpCpcReport(this.addOrUpdateForm).then(data => {
                this.addOrUpdateDialogVisible = false;
                this.getData();
            });
        },
        update: function () {
            updateDpCpcReport(this.addOrUpdateForm).then(data => {
                this.addOrUpdateDialogVisible = false;
                this.getData();
            });
        },
        onDelete: function (row) {
            this.$confirm('请确认是否删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteDpCpcReport({id: row.id}).then(data => {
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    this.getData();
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        addOrUpdateConfirm: function () {
            if (this.addOrUpdateDialogTitle == '新增') {
                this.add();
            } else if (this.addOrUpdateDialogTitle == '编辑') {
                this.update();
            }
        },
        // 获取表格数据
        getData: function () {
            this.$refs.shopDimension.getData();
            this.$refs.launchDimension.getData();
            this.$refs.keywordDimension.getData();
            this.$refs.allDimension.getData();
        },
        // 获取字段
        getFields() {
            getDpCpcPlanFields({}).then(data => {
                this.fields = data.body;
            })
        },
        // 获取推广计划
        getPlans() {
            let params = {};
            params.shopId = this.shopId;
            getDpCpcPlanByShopId(params).then(data => {
                this.plans = data.body;
                if (this.plans.length >= 0) {
                    this.plans.unshift({"launchId": 0, "launchName": "全部推广"})
                }
            });
        }
    },
    created() {
        if (this.launchId) {
            this.condition.search.launchId = this.launchId;
        }
        this.getPlans();
    },
}
</script>

<style scoped>
.el-input {
    width: 150px !important;
}

.el-select {
    width: 150px !important;
}
</style>
